package com.ysxsoft.wdg.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;

import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.umeng.socialize.UMShareAPI;
import com.ysxsoft.wdg.R;
import com.ysxsoft.wdg.base.BaseFragment;
import com.ysxsoft.wdg.net.UrlHost;
import com.ysxsoft.wdg.pay.PayPopWindow2;
import com.ysxsoft.wdg.ui.activity.center_zy.GoodsDetailActivity;
import com.ysxsoft.wdg.util.JavaInterface;
import com.ysxsoft.wdg.util.ObserverMap;
import com.ysxsoft.wdg.widget.SharePopupWindow;

import butterknife.BindView;

import static android.app.Activity.RESULT_CANCELED;
import static android.app.Activity.RESULT_OK;

public class TTaoWebFragment extends BaseFragment implements ObserverMap.IPageDataChangeObserver {

    @BindView(R.id.webView)
    com.tencent.smtt.sdk.WebView webView;
    @BindView(R.id.topView)
    View topView;
    @BindView(R.id.parent)
    LinearLayout parent;
    private SharePopupWindow popupWindow;
    private UMShareAPI mShareAPI;
    private PayPopWindow2 payPopWindow;
//    private String mainUrl = "http://zhwdg.sanzhima.cn/index.html#/headerdd";
    private String mainUrl = UrlHost.BASE_WEB_URL+"/dist/index.html#/headerdd";
//    private String mainUrl = "http://192.168.1.101:8080/#/commodityDetails?gid=36&uid=37&flag=1";
//        private String mainUrl = "http://192.168.1.101:8081/#/headerdd";
//    private String paySuccessUrl = "http://192.168.1.101:8080/#/";
    public static final int CHOOSE_PHOTO = 0x05;

    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    @Override
    protected int getLayoutId() {
        return R.layout.fm_two_web;
    }

    @Override
    protected void initData() {
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);

        ObserverMap.reg("TTaoWebFragment", this);
        initStatusBar(topView, false);
//        WebViewUtils.initNoInitFocusable(webView);
        webView.addJavascriptInterface(new JavaInterface(), "aa");
//        initX5();

        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setBlockNetworkImage(false);
        webView.getSettings().setAllowFileAccess(true);//设置可以访问文件
        webView.getSettings().setDatabaseEnabled(true);

        webView.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient());
        webView.setWebChromeClient(new WebChromeClient() {
            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                TTaoWebFragment.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                TTaoWebFragment.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("test", "openFileChooser 3");
                TTaoWebFragment.this.uploadFile = uploadFile;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
                TTaoWebFragment.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }
        });

        webView.loadUrl(mainUrl);
        webView.requestFocus();
    }

//    private void openFileChooseProcess() {
//        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
//        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
//        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");
//
//        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(getActivity())
//                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                .maxChooseCount(1) // 图片选择张数的最大值
//                .selectedPhotos(null) // 当前已选中的图片路径集合
//                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
//                .build();
//        startActivityForResult(photoPickerIntent, CHOOSE_PHOTO);
//    }

    private void initX5() {
        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        webSetting.setSupportZoom(true);
        webSetting.setBuiltInZoomControls(true);
        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        webSetting.setGeolocationEnabled(true);

        webSetting.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        webSetting.setBlockNetworkImage(false); // 解决图片不显示
        webSetting.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSetting.setCacheMode(android.webkit.WebSettings.LOAD_NO_CACHE);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
    }

    @Override
    public void change() {
    }

    @Override
    public void share(String gid, String url) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                popupWindow.setShareData(getString(R.string.app_name), url, url, "", 0);
                popupWindow.show(parent);
            }
        });
    }

    @Override
    public void share2(String gid, String url) {

    }

    private int type = 1;//1.团购 2砍价 3满减

    @Override
    public void pay(String orderId, String totalMoney, int type, String url) {
    }

    @Override
    public void back() {
        //暂未用到   KanWebViewActivity 返回事件回调
    }

    public void goBack(){
        if(webView.canGoBack()){
            webView.goBack();
        }
    }

    public boolean canGoBack(){
        return webView.canGoBack();
    }

    @Override
    public void toPinOrderDetail(String id) {
        //点击标签跳转到商品详情
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                GoodsDetailActivity.start(mContext, id);
            }
        });
    }

    @Override
    public void toKanOrderDetail(String id) {

    }

    private void openFileChooseProcess() {
//        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
//        // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
//        File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "BGAPhotoPickerTakePhoto");
//        Intent photoPickerIntent = new BGAPhotoPickerActivity.IntentBuilder(getActivity())
//                .cameraFileDir(takePhotoDir) // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话则不开启图库里的拍照功能
//                .maxChooseCount(1) // 图片选择张数的最大值
//                .selectedPhotos(null) // 当前已选中的图片路径集合
//                .pauseOnScroll(false) // 滚动列表时是否暂停加载图片
//                .build();
//        startActivityForResult(photoPickerIntent, 0);
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.e("tag", "是否有值：" + data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFile.onReceiveValue(result);
                        uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                        uploadFiles.onReceiveValue(new Uri[]{result});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }
            if (null != uploadFiles) {
                Uri result = (data == null || resultCode != RESULT_OK )? null:data.getData();
                if(result!=null){
                    uploadFiles.onReceiveValue(new Uri[]{result});
                }else{
                    uploadFiles.onReceiveValue(null);
                }
                uploadFiles = null;
            }
        }
        webView.requestFocus();

    }

    @Override
    protected void setListener() {

    }

    public void reset() {
        if (webView != null) {
            webView.loadUrl(mainUrl);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        ObserverMap.remove("TTaoWebFragment");
    }

}
